import Vue from 'vue'
import VueRouter from 'vue-router'
import common from '@/utils/common'
import { Message } from 'element-ui'
import routes from './routers'

Vue.use(VueRouter)

// 解决路由冗长
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  window.scrollTo(0, 0) // 每次路由跳转前都将页面滚动到顶部
  if (to.meta.isSignIn) {
    if (!common.getStorage('token')) {
      Message.error({
        message: '您还没有登录，请先登录后在操作！'
      })
      setTimeout(() => {
        next({ name: 'Login' })
      }, 1000 * 1.5)
      return false
    }
    next()
    return false
  }
  next()
})

export default router
